<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
        left: 0px;
        top: 0px;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <script>
      var boxEle = document.querySelector(".box");
      //拖拽开始：
      boxEle.onmousedown = function (event) {
        var e = event || window.event;
        var x = e.clientX - boxEle.offsetLeft;
        var y = e.clientY - boxEle.offsetTop; //按下的时候 获取box偏移量offsetleft 以及事件源的坐标e.clientx（鼠标点在的位置相对于界面的坐标），来计算光标在box中的相对坐标  x y
        //拖拽过程：
        boxEle.onmousemove = function (event) {
          var event = event || window.event; //实时获得事件源相对界面的位置  算出left top值 给盒子
          var disx = event.clientX - x;
          var disy = event.clientY - y;
          boxEle.style.left = disx + "px";
          boxEle.style.top = disy + "px";
        };
      };
      // 拖拽结束：在页面中当鼠标抬起的时候 清空掉  move事件
      document.onmouseup = function () {
        boxEle.onmousemove = "";
      };
    </script>
  </body>
</html>
